//
//  UserCacheManagement.swift
//  DaRings
//
//  Created by 易先生 on 2022/10/29.
//

import UIKit

open class UserCacheManagement: NSObject {

    public static let kUserInfoKey = "userInfo"

    open class func updateUserInfo(_ userInfo: UserModel) {
        
        var userInfo = userInfo
        if userInfo.steplength == 0 {
            userInfo.steplength = userInfo.getStepLength(height: userInfo.height)
        }
        
        if let json = userInfo.toJSON() {
            addDataToUserDefaults(kUserInfoKey, json)
        }
    }

    open class func userInfo() -> UserModel {
        
        guard let userModel = UserModel.deserialize(from: dataFormUserDefaults(kUserInfoKey)) else { return UserModel() }
        return userModel
    }
    

    open class func removeUserInfo() {
        removeDataToUserDefaults(kUserInfoKey)
    }
}


extension UserCacheManagement {
    /// 设置缓存数据
    /// - Parameters:
    ///   - key: key
    ///   - value: value
    public class func addDataToUserDefaults(_ key: String,
                                     _ value: [String : Any]?) {
        let userDefaults = UserDefaults.standard
        userDefaults.setValue(value, forKey: key)
        userDefaults.synchronize()
    }
    /// 获取缓存数据
    /// - Parameter key: key
    /// - Returns: data
    public class func dataFormUserDefaults(_ key: String) -> [String : Any]? {
        let userDefaults = UserDefaults.standard
        return userDefaults.value(forKey: key) as? [String : Any]
    }
    
    /// 删除缓存数据
    /// - Parameters:
    ///   - key: key
    public class func removeDataToUserDefaults(_ key: String) {
        let userDefaults = UserDefaults.standard
        userDefaults.removeObject(forKey: key)
        userDefaults.synchronize()
    }
}
